<?php

namespace app\api\Logic\Course;

use app\api\Logic\Campusclass\CampusClassLogic;
use app\api\Logic\Campusclass\CampusClassStudentLogic;
use app\api\model\CampusCourseOrderModel;
use app\api\model\CampusCourseOrderSublevelModel;
use app\api\model\PayLogModel;
use app\api\model\UserModel;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;

class ManagementPackageOrderLogic
{
    /**
     * 支付成功，用于支付成功回调用
     * @param $params
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function payment($params){
        Db::startTrans();
        try {
            // 加锁获取订单信息
            $orderInfo = CampusCourseOrderModel::where('no', $params['out_trade_no'])
                ->field('id,shop_id,status')
                ->lock(true)
                ->find();
            $orderInfo = objToArray($orderInfo) ?? [];
            if (empty($orderInfo)) {
                return false;
            }
            if ($orderInfo['status'] != 1) {
                return false;
            }

            //加锁获取订单子项信息
            $orderSublevelList = CampusCourseOrderSublevelModel::where('no', $params['out_trade_no'])
                ->field('id,gs_id,type,m_type,m_type_num,all_num,status')
                ->lock(true)
                ->select();
            $orderSublevelList = objToArray($orderSublevelList) ?? [];
            if (empty($orderSublevelList)) {
                return false;
            }

            // 修改支付单信息
            $updateInfo = [
                'status' => 2,
                'pay_time' => time()
            ];
            CampusCourseOrderModel::where('no', $params['out_trade_no'])->update($updateInfo);

            //订单子项为课程并且单位为天或者月单位，则end_time有值
            foreach ($orderSublevelList as $sublevelOrderInfo){
                if($sublevelOrderInfo['type'] == 3){
                    $startTime = time();
                    $endTime = 0;
                    if ($sublevelOrderInfo['m_type'] == 'monthly') {
                        //todo 这边一个月默认30天，若需严格按照日历天数，则另写接口计算
                        $endTime = $startTime + $sublevelOrderInfo['all_num'] * 30 * 3600 * 24;
                    } else if ($sublevelOrderInfo['m_type'] == 'day') {
                        $endTime = $startTime + $sublevelOrderInfo['all_num'] * 24 * 3600;
                    }

                    // 修改订单子项信息
                    $updateSublevelData = [
                        'status' => 1,
                        'start_time' => $startTime,
                        'end_time' => $endTime
                    ];

                    //获取课程详情
                    $managementLogic = new ManagementLogic();
                    $courseInfo = $managementLogic->managementInfo($sublevelOrderInfo['gs_id']);
                    //如果课程是一对一，则生成对应记录
                    if($courseInfo['class_type'] == 2){
                        $campusClassLogic = new CampusClassLogic();
                        $campusClassStudentLogic = new CampusClassStudentLogic();
                        //获取用户信息
                        $userInfo = UserModel::where('id',$orderInfo['user_id'])
                            ->field('id,truename')
                            ->find();
                        $userInfo = objToArray($userInfo) ?? [];
                        $userName = $userInfo['truename'] ?? '';
                        //生成一个新的班级
                        $classId = $campusClassLogic->createOneOnOneClass([
                            'shop_id' => $orderInfo['shop_id'],
                            'name' => $courseInfo['name'].'_'.$userName,
                            'course_id' => $courseInfo['id']
                        ]);

                        //生成班级学员记录
                        $campusClassStudentLogic->insert([
                            'shop_id' => $orderInfo['shop_id'],
                            'class_id' => $classId,
                            'user_id' => $userInfo['id'],
                            'course_id' => $courseInfo['id'],
                            'all_class_hour' => $sublevelOrderInfo['all_num']
                        ]);
                    }

                }else{
                    $updateSublevelData = [
                        'status' => 1
                    ];
                }
                CampusCourseOrderSublevelModel::where('id', $params['id'])->update($updateSublevelData);
            }

            //查询主订单ID
            $payLogInfo = PayLogModel::where('controller','course/management_package_order')
                ->where('order_id',$orderInfo['id'])
                ->where('shop_id',$orderInfo['shop_id'])
                ->field('id,coupon_id')
                ->find();
            $payLogInfo = objToArray($payLogInfo) ?? [];
            if(!empty($payLogInfo)){
                //todo 执行优惠券核销动作，优惠券状态改成已使用等，待接口，后面补上

                //todo 额外数据，用于保存交易单号等信息，由于不知道回调返回的参数，因此这边暂时为空
                $expandData = [
                    'transaction_id' => ''
                ];
                //执行主订单回调
                $this->payLogNotify($payLogInfo['id'],$expandData);
            }

            Db::commit();
            return true;
        } catch (Exception $e) {
            Db::rollback();
            return false;
        }
    }

    /**
     * 主订单回调
     * @param $orderId
     * @param null $expandData
     * @return false
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function payLogNotify($orderId,$expandData = null){
        // 加锁获取订单信息
        $orderInfo = PayLogModel::where('id', $orderId)
            ->lock(true)
            ->find();
        $orderInfo = objToArray($orderInfo) ?? [];
        if (empty($orderInfo)) {
            return false;
        }
        if ($orderInfo['status'] != 0) {
            return false;
        }

        // 修改支付单信息
        $updateInfo = [
            'status' => 1,
            'pay_time' => time()
        ];
        $updateInfo = array_merge($expandData,$updateInfo);

        PayLogModel::where('id', $orderId)->update($updateInfo);

        return true;
    }

    /**
     * 套餐课程列表
     * @param $params
     * @param bool $isLimit
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function orderList($params,$isLimit = false){
        $query = CampusCourseOrderModel::where('shop_id',$params['shop_id'])
            ->where('user_id',$params['user_id'])
            ->where('style',2)
            ->where('status',2)
            ->with([
                'mallGoodsInfo' => function ($query) {
                    $query->withField('id,name,price,cost_price,image');
                },
                'managementPackageOrderList' => function ($query) {
                    $query->where('type',3)
                        ->withField('no,type,gs_id,m_type,m_type_num,status,all_num,use_num,start_time,end_time');
                }
            ])->field('id,no,style,price,name,image,status,goods_id')
            ->order('createtime','desc');

        //分页
        if($isLimit){
            $list = $query->paginate(PAGE_SIZE);
            $res = objToArray($list) ?? [];
        }else{
            $list = $query->select();
            $res['data'] = objToArray($list) ?? [];
        }

        return $res;
    }
}
